//
//  UIViewController+Tool.m
//  UILbrary
//
//  Created by Apple on 2023/3/4.
//  Copyright © 2023 mac. All rights reserved.
//

#import "UIViewController+Tool.h"

@implementation UIViewController (Tool)


+ (void)showAelrtWithTitle:(NSString *)title
{
    if(!title) return;
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示"
                                                                     message:title
                                                              preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * _Nonnull action) {}];
    [alertVC addAction:action];
    
    [[UIViewController currentVC] presentViewController:alertVC animated:YES completion:nil];
}


//获取当前屏幕显示的viewcontroller
+ (UIViewController *)currentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];

    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;

    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的

        rootVC = [rootVC presentedViewController];
    }

    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController

        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];

    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController

        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];

    }
    else {
        // 根视图为非导航类

        currentVC = rootVC;
    }

    return currentVC;
}


@end
